import React, { useState, useCallback, useEffect } from 'react';
import { Editor } from '@tiptap/react';

interface ColorPickerProps {
  editor: Editor;
  type: 'text' | 'highlight';
  title?: string;
  icon: string;
}

const ColorPicker: React.FC<ColorPickerProps> = ({ editor, type, title, icon }) => {
  const [isOpen, setIsOpen] = useState(false);
  const [customColor, setCustomColor] = useState('#000000');

  const colors = [
    ['#000000', '#e60000', '#ff9900', '#ffff00', '#00ff00', '#00ffff', '#4a86e8', '#9900ff'],
    ['#e6e6e6', '#f4cccc', '#fce5cd', '#fff2cc', '#d9ead3', '#d0e0e3', '#cfe2f3', '#d9d2e9'],
    ['#666666', '#cc0000', '#e69138', '#f1c232', '#6aa84f', '#45818e', '#3d85c6', '#674ea7'],
  ];

  const handleColorClick = useCallback((color: string) => {
    if (type === 'text') {
      editor.chain().focus().setColor(color).run();
    } else {
      editor.chain().focus().setHighlight({ color }).run();
    }
    setIsOpen(false);
  }, [editor, type]);

  const getCurrentColor = useCallback(() =>
    type === 'text'
      ? editor.getAttributes('textStyle').color || '#000000'
      : editor.getAttributes('highlight').color || 'transparent'
    , [editor, type]);

  // 添加点击外部关闭的处理
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (!target.closest('.color-picker-container')) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  return (
    <div className="color-picker-container">
      <button
        className="toolbar-button"
        onClick={() => setIsOpen(!isOpen)}
        title={title}
      >
        <span className="color-indicator" style={{ backgroundColor: getCurrentColor() }}>
          {icon}
        </span>
      </button>

      {isOpen && (
        <div className="color-picker-dropdown">
          <div className="color-grid">
            {colors.map((row, i) => (
              <div key={i} className="color-row">
                {row.map(color => (
                  <button
                    key={color}
                    className="color-cell"
                    style={{ backgroundColor: color }}
                    onClick={() => handleColorClick(color)}
                  />
                ))}
              </div>
            ))}
          </div>
          <div className="color-picker-footer">
            <div className="color-input-wrapper">
              <span>自定义颜色</span>
              <input
                type="color"
                className="color-input"
                value={customColor}
                onChange={e => {
                  const newColor = e.target.value;
                  setCustomColor(newColor);
                  handleColorClick(newColor);  // 直接应用颜色
                }}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ColorPicker;